package com.qiandw.security.config;

import com.qiandw.repo.security.RoleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author coxx
 */

@Configuration
public class SecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {


    private final RoleRepo repo;

    @Autowired
    public SecurityMetadataSourceImpl(RoleRepo repo) {
        this.repo = repo;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HashSet<ConfigAttribute> attributes = new HashSet<>();
        FilterInvocation filterInvocation = ((FilterInvocation) object);
        repo.findAll().forEach(role -> role.getAuthorities().forEach(authority -> {
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(authority.getUrl());
            if(matcher.matches(filterInvocation.getRequest())){
                attributes.add(new SecurityConfig(role.getName()));
            }
        }));
        return attributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return new HashSet<>();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
